/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
#pragma clang diagnostic ignored "-Wincompatible-pointer-types"

#include "ParameterCheck.h"
#include "OSMemory.h"
#include "IpcService.h"
#include "IpcSimService.pb-c.h"
#include "IpcSimServiceDispatcher.h"

typedef struct {
    IpcServiceClientData ipcClient;
} IpcSimClientData;

#define MSG_ID_SIM_STATE_CHANGED_IND 0

static void IpcSimServiceInitClient(IpcService* service, void* clientData) {
}

IPC_RESULT ipcSimServiceHandleGetSimState(IpcTransaction* transaction, void* clientData, void* data, int dataLen) {
    PARAMTER_CHECK_RETURN_VALUE(transaction && clientData, IPC_RESULT_INVALID_PARAMETER);
    IpcSimClientData* client = clientData;
    PARAMTER_CHECK_RETURN_VALUE(client->ipcClient.subId >=0 && client->ipcClient.subId <= 1, IPC_RESULT_INVALID_PARAMETER);
    IpcService* service = SERVICE_FROM_TRANSACTION(transaction);
    IpcGetSimStateResponse response = IPC_GET_SIM_STATE_RESPONSE__INIT;
    if (client->ipcClient.subId == 0) {
        response.state = 1;
    } else {
        response.state = 3;
    }
    int protoDataSize = ipc_get_sim_state_response__get_packed_size(&response);
    uint8_t* protoData = (uint8_t*)OS_MALLOC(protoDataSize);
    ipc_get_sim_state_response__pack(&response, protoData);
    ipcSendResponse(transaction, IPC_RESULT_OK, protoData, protoDataSize);
    return IPC_RESULT_OK;
}

void sendSimStateChanged(IpcService* service, int channelId, int msgId, void* data, int dataLen) {
    ipcSendIndication(service, 0, MSG_ID_SIM_STATE_CHANGED_IND, NULL, 0);
}

IpcService* newIpcSimService() {
    IpcService* service = newIpcService(IPC_SERVICE_SIM, ipc_sim_request__unpack, ipc_sim_request__free_unpacked);
    registerDispatchTable(service, simServiceDispatchTable, ARRAY_SIZE(simServiceDispatchTable));
    service->ops.initClientCb = IpcSimServiceInitClient;
    service->clientDataSize = sizeof(IpcSimClientData);
    return service;
}

